#!/bin/env python
# coding: utf-8
__author__ = 'donvan'
__date__ = '7/22/14'
import datetime
import subprocess
import logging
import os
import sys
import zipfile
from StringIO import StringIO
import hashlib

base_path = os.path.dirname(os.path.abspath(__file__))
sys.path.append('%s/../donvan_site' % base_path)

import settings
logging.basicConfig(format='%(asctime)s - %(levelname)-7s - %(filename)s:%(funcName)s:%(lineno)s - %(message)s',
                    datefmt='%Y-%m-%d %H:%M:%S',
                    level=logging.DEBUG)
from my_email import Mail
import priviate_data

now = datetime.datetime.now()


def dump_db_data():
    db_name = settings.DATABASES["default"]["NAME"]
    db_user = settings.DATABASES["default"]["USER"]
    db_password = settings.DATABASES["default"]["PASSWORD"]
    db_host = settings.DATABASES["default"]["HOST"]
    db_port = settings.DATABASES["default"]["PORT"]

    command = 'mysqldump -u%s -p%s -h%s -P%s %s' % (db_user, db_password, db_host, db_port, db_name)
    p = subprocess.Popen(command, shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
    db_data, db_stderr = p.communicate()
    if p.returncode == 0:
        return db_data
    else:
        logging.error(db_stderr)


def zip_data(data):
    buf = StringIO()
    db_zip = zipfile.ZipFile(buf, 'w', zipfile.ZIP_DEFLATED)
    db_zip.writestr('%s.sql' % now.strftime('%Y-%m-%d_%H-%M-%S'), data)
    db_zip.close()
    return buf.getvalue()


def backup_media():
    media_path = "%s/../media" % base_path
    media_check_file = "%s/media.check_file" % base_path
    if os.path.exists(media_check_file):
        with open(media_check_file) as f:
            old_media_checksum = f.read()
    else:
        old_media_checksum = None
    sf = StringIO()
    zf = zipfile.ZipFile(sf, 'w', zipfile.ZIP_DEFLATED)
    for root, dirs, files in os.walk(media_path):
        for file in files:
            zf.write(os.path.join(root, file))
    zf.close()
    sf_value = sf.getvalue()
    sf.close()
    new_media_checksum = hashlib.md5(sf_value).hexdigest()
    if new_media_checksum == old_media_checksum:
        return None
    else:
        with open(media_check_file, 'w') as f:
            f.write(new_media_checksum)
        return sf_value


def send_mail():
    mail = Mail()
    mail.sender = "413477218@qq.com"
    mail.receiver = ("donvan@163.com", )
    mail.subject = '[%s] donvan site backup' % now.strftime('%Y-%m-%d %H:%M:%S')
    # mail.attach_files = None
    mail.smtp_server = "smtp.qq.com"
    mail.username = priviate_data.qq_mail_username
    mail.password = priviate_data.qq_mail_password
    mail.content_as_html = '''
    <h1>RT</h1>
    '''
    mail.add_file('mysql.%s.zip' % now.strftime('%Y-%m-%d_%H-%M-%S'), zip_data(dump_db_data()))
    media_data = backup_media()
    if media_data:
        mail.add_file('media.%s.zip' % now.strftime('%Y-%m-%d_%H-%M-%S'), media_data)
    mail.send()
    logging.info("success.")


if __name__ == "__main__":
    send_mail()
